<template>

  <div class="content">
    <van-cell-group inset>
      <van-field label="投票主题" v-model=topic readonly />
    </van-cell-group>

    <div class="option">
      <van-radio-group v-model="checked">
        <van-cell-group inset>
          <van-cell :key="index" :title=item.name clickable @click="checked = index"
            v-for="(item, index) in optionsArr">
            <template #right-icon>
              <van-radio :name=index />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </div>
  </div>

  <div class="submitBtn">
    <van-button :disabled="isSubmit" @click="subOption" type="primary" block>{{ isSubmit ? "已提交" : "投票" }}</van-button>
  </div>

  <!-- <div class="result" v-show="isSubmit"> -->
  <div class="result">
    <van-divider>投票结果</van-divider>

    <van-cell-group inset>
      <van-field :key="index" :label=item.name :model-value=item.voteCount readonly
        v-for="(item, index) in optionsArr" />
    </van-cell-group>
  </div>

</template>

<script>
import { onMounted, ref } from "vue";
import useWeb3 from '../util.js';

const { ballotSm, web3 } = useWeb3();
const host = ref("");
const topic = ref("");
const optionsArr = ref([]);
const checked = ref(0);
const isSubmit = ref(false);

// 导航栏的选中状态
const active = ref(0);

const getHost = async () => {
  host.value = await ballotSm.methods.chairperson().call();
}

const getTopic = async () => {
  topic.value = await ballotSm.methods.topic().call();
}

const getOptions = async () => {
  const arr = await ballotSm.methods.getList().call();
  optionsArr.value = arr;
}

const subOption = async () => {
  console.log(checked.value);
  // const accounts = await window.ethereum.send("eth_requestAccounts");
  const accounts = await web3.eth.getAccounts();
  const defaultAccount = accounts[0];
  console.log("defaultAccount", defaultAccount);
  console.log("type", typeof checked.value);

  const receipt = await ballotSm.methods.vote(checked.value).send({
    from: defaultAccount,
    gas: 1000000,
    gasPrice: '10000000000',
  })
  console.log("receipt", receipt);
  isSubmit.value = true;
  getOptions();
}



export default {
  name: 'BallotView',
  components: {

  },
  setup() {
    onMounted(async () => {
      console.log(`the component is now mounted.`);
      await getHost();
      await getTopic();
      await getOptions();
    })
    return {
      host,
      topic,
      optionsArr,

      active,
      isSubmit,
      subOption,
      checked,
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.content {
  margin-top: 32px;
}

.option {
  margin-top: 16px;
}

.submitBtn {
  padding: 16px 32px;
}

.result {
  width: 50%;
  margin: 0 auto;
}
</style>